package com.can.Service.Impl;

import com.can.Mapper.RepliesMapper;
import com.can.Service.ReplyService;
import com.can.domain.Dto.CreateReplyDto;
import com.can.domain.po.Replies;
import com.can.domain.vo.RepliesVo;
import com.can.domain.vo.postcommonvo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


@Service
public class replyImpl implements ReplyService {

    @Autowired
    RepliesMapper repliesMapper;


    //    查帖子的回复
    @Override
    public postcommonvo getRepliesByPostId(int postId) {
        try {

            List<RepliesVo> allReplies = repliesMapper.getRepliesByPostId(postId);
//            System.out.println(repliesVoList);
            //建立父子关系
            ArrayList<Object> res = new ArrayList<>();
            HashMap<Integer, RepliesVo> map = new HashMap<>();
            for (RepliesVo reply : allReplies) {
                map.put(reply.getId(), reply);
            }
            for (RepliesVo reply : allReplies) {
                if (reply.getParentReplyId()==null){
                    res.add(reply);
                }else {map.get(reply.getParentReplyId()).getChildren().add(reply);}
            }
//            System.out.println("结果："+res);

//            System.out.println(allReplies);
            return new postcommonvo(200,"查询成功",res);

        }catch (Exception e){
            e.printStackTrace();
            return new postcommonvo(400,"查询失败",null);
        }
    }

    @Override
    public postcommonvo CreateReply(CreateReplyDto repliesDto) {
        System.out.println("发表回复数据："+repliesDto.toString());

        try {
            Replies reply = new Replies();
            BeanUtils.copyProperties(repliesDto, reply);
            System.out.println("插入的数据是"+reply.toString());
            repliesMapper.insert(reply);
            return new postcommonvo(200,"回复成功",null);
        }catch (Exception e){
            e.printStackTrace();
            return new postcommonvo(400,"回复失败",null);
        }
    }


}
